package com.uxsino.simo.incremental.parser;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.uxsino.reactorq.model.IndicatorValue;
import com.uxsino.simo.incremental.IncrementalParser;
import com.uxsino.simo.incremental.IncrementalUtil;
import org.apache.commons.lang3.StringUtils;

public class MemoryParser implements IncrementalParser {

    @Override
    public void apply(IndicatorValue oldValue, IndicatorValue value) {
        if (value == null) {
            return;
        }
        Double memTotal = null;
        String key = value.entityId;
        Object obj = JSONArray.toJSON(value.value);
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            memTotal = json.getDouble("memory_total");
        } else if (obj instanceof JSONArray) {
            JSONArray array = (JSONArray) obj;
            for (int i = 0; i < array.size(); i++) {
                JSONObject json = array.getJSONObject(i);
                if (json.containsKey("physical_memory_total")) {
                    memTotal = json.getDouble("physical_memory_total");
                    break;
                } else if (StringUtils.isBlank(json.getString("memory_name"))
                        || "Physical Memory".equalsIgnoreCase(json.getString("memory_name"))
                        || "Mem:".equalsIgnoreCase(json.getString("memory_name"))) {
                    memTotal = json.getDouble("memory_total");
                    break;
                } else if ("Virtual Memory".equalsIgnoreCase(json.getString("memory_name"))) {
                    memTotal = json.getDouble("memory_total");
                }
            }
        }
        IncrementalUtil.putMemTotalCache(key, memTotal);
    }
}
